package com.snail.common.mq.core;

import com.snail.common.core.exception.ServiceException;
import com.snail.common.core.utils.SpringUtils;
import com.snail.common.lock.Lock;
import com.snail.common.mq.core.dto.MqDto;
import com.snail.common.mq.core.dto.MqResultDto;
import com.snail.common.mq.exception.MqException;
import com.snail.common.mq.service.ISnailMqProducerService;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * @Description: MQ消息工厂
 * @Author: Snail
 * @CreateDate: 2023/11/21 11:29
 * @Version: V1.0
 */
public abstract class AbstractMqFactory<T> {

    @Autowired
    protected Lock lock;
    protected IMqProducerAndConsumerHandler mqProducerAndConsumerHandler;
    protected ISnailMqProducerService snailMqProducerService;

    protected AbstractMqFactory(IMqProducerAndConsumerHandler mqProducerAndConsumerHandler) {
        this.mqProducerAndConsumerHandler = mqProducerAndConsumerHandler;
        try {
            this.snailMqProducerService = SpringUtils.getBean(ISnailMqProducerService.class);
        } catch (Exception e) {
            this.snailMqProducerService = null;
        }
    }


    /**
     * 发送mq消息
     *
     * @param mqDto 消息体
     * @return 结果
     * @throws MqException mq异常
     */
    protected MqResultDto sendMq(MqDto<T> mqDto) throws MqException {
        return new MqResultDto();
    }

    /**
     * 消息监听
     *
     * @param value 消息体
     * @throws MqException mq异常
     */
    protected abstract void listener(String value) throws MqException;

    /**
     * 业务消费处理
     *
     * @param mqDto 消息体
     * @throws ServiceException 业务异常
     * @throws MqException      mq异常
     */
    protected abstract void consumeMq(MqDto<T> mqDto) throws ServiceException, MqException;

    /**
     * 消息生产记录数
     *
     * @param mqDto 消息体
     * @return 结果
     * @throws ServiceException 业务异常
     * @throws MqException      mq异常
     */
    protected Long getProducerCount(MqDto<T> mqDto) throws ServiceException, MqException {
        if (snailMqProducerService != null) {
            return snailMqProducerService.selectMqProducerCount(mqDto);
        }
        return -1L;
    }

}
